import pandas as pd
import os
import requests
from datetime import datetime
from pymongo import MongoClient

import os, fnmatch

path = r'E:\risk\pyecharts\touceng\routin\merchant_black_list'
history = r'E:\risk\pyecharts\touceng\routin\merchant_black_list\history'

files = []


def read_names():
    names = []
    pattern = "*.xlsx"
    for file in os.listdir(path):
        full_name = os.path.join(path, file)
        if os.path.isfile(full_name) and fnmatch.fnmatch(file, pattern):
            files.append(file)
            data = pd.read_excel(full_name)
            names = names + data.ix[:, 0].tolist()
    print(len(names))
    print(files)
    return names


def read_docs(names):
    client = MongoClient('localhost', 27017)

    db = client['bigdata']
    col = db['bigdata_decision_table_data']

    query = {"decisionTableNo": "301", "values.merchantName": {"$in": names}}

    fields = {"keys.merchantCode": 1, "values.areaCode": 1, "values.agencyId": 1, "values.merchantName": 1}

    return col.find(query, fields)


def post_risk(docs):
    url = "http://150.109.38.70:8080/bigdata-ws/rest/riskverify"
    print(docs.count())
    for doc in docs:
        dt = datetime.now()
        print
        '时间：(%Y-%m-%d %H:%M:%S %f): ', dt.strftime('%Y-%m-%d %H:%M:%S %f')

        event = {"checkPoint": "TCMerchant001", "appId": "merchant_block_gmail", "requestTime": dt.strftime('%Y-%m-%d '
                                                                                                            '%H:%M:%S'),
                 "eventBody": {
                     "merchantID": doc['keys']['merchantCode'],
                     "merchantLocationCode": doc['values']['areaCode'],
                     "agencyID": doc['values']['agencyId'],
                     "merchantName": doc['values']['merchantName'],
                     "status": 99
                 }}
        print(event)
        r = requests.post(url, json=event)
        if r.status_code != 200:
            print("error" + doc['values']['merchantName'])


def move_history(files):
    for file in files:
        os.rename(os.path.join(path, file),
                  os.path.join(history, file))


# main


names = read_names()
docs = read_docs(names)
post_risk(docs)
move_history(files)
